// src/store/user.js
import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
  state: () => ({
    // 登录响应信息
    loginResponse: {
      code: null,
      message: "",
      data: null,
    },
    // 用户信息
    userInfo: {
      id: null,
      account: "",
      email: "",
      role: null,
      status_code: null,
      rest_time: null,
      last_land_time: null,
      created_at: "",
      updated_at: "",
      realname: "",
      address: "",
      tel: null,
      institution: "",
      time: "",
      total_time: null,
      photourl0: null,
      photourl1: null,
      photourl2: null,
      class_id: null,
      faceTotalTime: null,
      university_id: null,
      failed_land_number: null,
      failed_land_time: "",
      isLoggedIn: false,
    },
    // 用户设置
    settings: {
      theme: "light",
      language: "zh",
    },
    // 用户在currentUsers数组中的位置
    copyNum: 0,
    // 控制权剩余时间（秒）
    timeLeft: 0,
  }),

  getters: {
    // 获取用户是否已登录
    isLogin: (state) => state.userInfo.isLoggedIn,

    // 获取用户名
    userName: (state) => state.userInfo.account,

    // 获取用户真实姓名
    userRealName: (state) => state.userInfo.realname,

    // 获取用户角色
    userRole: (state) => state.userInfo.role,

    // 获取登录响应码
    loginCode: (state) => state.loginResponse.code,

    // 获取登录消息
    loginMessage: (state) => state.loginResponse.message,

    // 获取用户在currentUsers数组中的位置
    getCopyNum: (state) => state.copyNum,
    // 获取控制权剩余时间（秒）
    getTimeLeft: (state) => state.timeLeft,
  },

  actions: {
    // 用户登录
    login(loginResponse) {
      // 保存完整的登录响应
      this.loginResponse = {
        code: loginResponse.code,
        message: loginResponse.message,
        data: loginResponse.data,
      };

      // 如果登录成功，保存用户信息
      if (loginResponse.code === 100 && loginResponse.data) {
        // 确保将返回数据中的所有字段完整保存到user对象中
        this.userInfo = {
          id: loginResponse.data.id,
          account: loginResponse.data.account,
          email: loginResponse.data.email,
          role: loginResponse.data.role,
          status_code: loginResponse.data.status_code,
          rest_time: loginResponse.data.rest_time,
          last_land_time: loginResponse.data.last_land_time,
          created_at: loginResponse.data.created_at,
          updated_at: loginResponse.data.updated_at,
          realname: loginResponse.data.realname,
          address: loginResponse.data.address,
          tel: loginResponse.data.tel,
          institution: loginResponse.data.institution,
          time: loginResponse.data.time,
          total_time: loginResponse.data.total_time,
          photourl0: loginResponse.data.photourl0,
          photourl1: loginResponse.data.photourl1,
          photourl2: loginResponse.data.photourl2,
          class_id: loginResponse.data.class_id,
          faceTotalTime: loginResponse.data.faceTotalTime,
          university_id: loginResponse.data.university_id,
          failed_land_number: loginResponse.data.failed_land_number,
          failed_land_time: loginResponse.data.failed_land_time,
          isLoggedIn: true,
        };

        // 持久化存储到localStorage
        this.persistUserData();
      }
    },

    // 用户登出
    logout() {
      this.loginResponse = {
        code: null,
        message: "",
        data: null,
      };

      this.userInfo = {
        id: null,
        account: "",
        email: "",
        role: null,
        status_code: null,
        rest_time: null,
        last_land_time: null,
        created_at: "",
        updated_at: "",
        realname: "",
        address: "",
        tel: null,
        institution: "",
        time: "",
        total_time: null,
        photourl0: null,
        photourl1: null,
        photourl2: null,
        class_id: null,
        faceTotalTime: null,
        university_id: null,
        failed_land_number: null,
        failed_land_time: "",
        isLoggedIn: false,
      };

      // 重置copyNum
      this.copyNum = -1;

      // 重置timeLeft
      this.timeLeft = 0;

      // 清除localStorage中的用户数据
      localStorage.removeItem("loginResponse");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("isLoggedIn");
      localStorage.removeItem("copyNum");
      localStorage.removeItem("timeLeft");
    },

    // 更新用户设置
    updateSettings(settings) {
      this.settings = {
        ...this.settings,
        ...settings,
      };
    },

    // 持久化用户数据到localStorage
    persistUserData() {
      localStorage.setItem("loginResponse", JSON.stringify(this.loginResponse));
      localStorage.setItem("userInfo", JSON.stringify(this.userInfo));
      localStorage.setItem("isLoggedIn", "true");
    },

    // 从localStorage恢复用户数据
    restoreUserData() {
      try {
        const savedLoginResponse = localStorage.getItem("loginResponse");
        const savedUserInfo = localStorage.getItem("userInfo");
        const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";

        if (savedLoginResponse) {
          this.loginResponse = JSON.parse(savedLoginResponse);
        }

        if (savedUserInfo) {
          this.userInfo = JSON.parse(savedUserInfo);
          this.userInfo.isLoggedIn = isLoggedIn;
        }
      } catch (error) {
        console.error("恢复用户数据失败:", error);
        this.logout();
      }
    },

    // 设置用户在currentUsers数组中的位置
    setCopyNum(copyNum) {
      this.copyNum = copyNum;
      // 持久化存储到localStorage
      localStorage.setItem("copyNum", String(copyNum));
    },

    // 从localStorage恢复copyNum
    restoreCopyNum() {
      try {
        const savedCopyNum = localStorage.getItem("copyNum");
        if (savedCopyNum !== null) {
          this.copyNum = parseInt(savedCopyNum, 10);
        }
      } catch (error) {
        console.error("恢复copyNum失败:", error);
        this.copyNum = -1;
      }
    },
    // 设置控制权剩余时间（秒）
    setTimeLeft(timeLeft) {
      this.timeLeft = timeLeft;
      // 持久化存储到localStorage
      localStorage.setItem("timeLeft", String(timeLeft));
    },
    // 恢复控制权剩余时间（秒）
    restoreTimeLeft() {
      try {
        const savedTimeLeft = localStorage.getItem("timeLeft");
        if (savedTimeLeft !== null) {
          this.timeLeft = parseInt(savedTimeLeft, 10);
        }
      } catch (error) {
        console.error("恢复timeLeft失败:", error);
        this.timeLeft = 0;
      }
    },
  },
});
